package com.moos.example;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.moos.example.adapter.RecyclerBaseAdapter;
import com.moos.example.bean.DiscussBean;
import com.moos.example.bean.DiscussDetailBean;
import com.moos.example.utils.HttpUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DiscussActivity extends AppCompatActivity implements View.OnClickListener {

    CollapsingToolbarLayout collapsingToolbar;
    private List<DiscussDetailBean> discussDetailBeanList;
    private RecyclerBaseAdapter adapter;
    private BottomSheetDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discuss);
        initView();
    }

    /**
     * func
     */
    private void initView() {
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        collapsingToolbar = findViewById(R.id.collapsing_toolbar);
        FloatingActionButton fab = findViewById(R.id.floatbutton);
        // 设置返回按钮
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        // 设置 toolbar
        collapsingToolbar.setTitle("社区讨论");
        fab.setOnClickListener(this);
        // 设置expandlistview
        requestData();
    }

    /**
     * 初始化评论和回复列表
     */
    private void setRecyclerView(final List<DiscussDetailBean> list) {

        RecyclerView recyclerView = findViewById(R.id.page_lv_comment);

        recyclerView.setLayoutManager(new LinearLayoutManager(DiscussActivity.this));

        adapter = new RecyclerBaseAdapter(this, (ArrayList<DiscussDetailBean>) list);

        recyclerView.setAdapter(adapter);

        // 设置跳转的指令
        adapter.setOnItemClickListener(position -> {
            System.out.println("Item print the POSITION --->" + position);
            Intent intent = new Intent(DiscussActivity.this, DetailActivity.class);
            DiscussDetailBean discussDetailBean = discussDetailBeanList.get(position);
            System.out.println(discussDetailBean);
            Gson gson = new Gson();
            String data = gson.toJson(discussDetailBean);
            intent.putExtra("data", data);
            startActivity(intent);
        });

        recyclerView.setItemAnimator(new DefaultItemAnimator());
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(DiscussActivity.this, DividerItemDecoration.VERTICAL);
        Drawable drawable = ContextCompat.getDrawable(DiscussActivity.this, R.color.colorAccent);
        assert drawable != null;
        dividerItemDecoration.setDrawable(drawable);
        recyclerView.addItemDecoration(dividerItemDecoration);
    }

    /**
     * func:生成测试数据
     *
     * @return 评论数据
     */
    private List<DiscussDetailBean> generateTestData() {
        DiscussBean discussBean;
        try {
            InputStream inputStream = getAssets().open("rrep.json");
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            Gson gson = new Gson();
            discussBean = gson.fromJson(inputStreamReader, DiscussBean.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return discussBean.getData().getList();
    }


    public void requestData() {
        String textUrl = "http://192.168.0.117:8081/showAllComments";
        HttpUtil.sendOkHttpRequest(textUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                System.out.println("onFailure-------------------------");
//                e.printStackTrace();
                runOnUiThread(() -> {
                    discussDetailBeanList = generateTestData();
                    setRecyclerView(discussDetailBeanList);
                    Toast.makeText(DiscussActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                //线程回到主线程，否则系统交出现错调
                runOnUiThread(() -> {
                    if (responseText != null) {
                        Gson gson = new Gson();
                        DiscussBean discussBean = gson.fromJson(responseText, DiscussBean.class);
                        discussDetailBeanList = discussBean.getData().getList();
                        setRecyclerView(discussDetailBeanList);
                    } else {
                        Toast.makeText(DiscussActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    // 可以设置返回的按钮
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.floatbutton) {
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                    .setAction("Action", null).show();
            showCommentDialog();
        }
    }


    /**
     * func:弹出评论框，给发布评论者评论
     */
    private void showCommentDialog() {
        // 初始化
        dialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") View commentView = LayoutInflater.from(this).inflate(R.layout.comment_discuss_layout, null);

        final EditText commentText = commentView.findViewById(R.id.dialog_comment_et);
        final EditText titleText = commentView.findViewById(R.id.dialog_title_et);
        final Button bt_comment = commentView.findViewById(R.id.dialog_comment_bt);
        dialog.setContentView(commentView);
        /*
          解决bsd显示不全的情况
         */
        View parent = (View) commentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        commentView.measure(0, 0);
        behavior.setPeekHeight(commentView.getMeasuredHeight());

        bt_comment.setOnClickListener(view -> {
            String commentContent = commentText.getText().toString().trim();
            String commenttitle = titleText.getText().toString().trim();
            if (!TextUtils.isEmpty(commentContent) && !TextUtils.isEmpty(commenttitle)) {
                // 关掉dialog
                dialog.dismiss();

                // 把评论数据插入
                DiscussDetailBean detailBean = new DiscussDetailBean();

                detailBean.setId(512);
                detailBean.setContent(commentContent);
                detailBean.setCreateDate("刚刚");
                detailBean.setTitle(commenttitle);
                detailBean.setUserLogo(null);
                detailBean.setReplyCount(0);
                detailBean.setRefs("./rep.json");
                detailBean.setNickName("小明");
                detailBean.setImgId("xcclsscrt0tev11ok364");

                System.out.println(detailBean);

                adapter.updateData(detailBean);

//                adapter.addTheCommentData(detailBean);


//                Toast.makeText(DiscussActivity.this, "发帖成功", Toast.LENGTH_SHORT).show();

                Toast toast = Toast.makeText(DiscussActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("发帖成功");
                toast.show();

            } else {
//                Toast.makeText(DiscussActivity.this, "发帖不能为空", Toast.LENGTH_SHORT).show();

                Toast toast = Toast.makeText(DiscussActivity.this, "", Toast.LENGTH_LONG);
                toast.setText("发帖不能为空");
                toast.show();
            }
        });

        // 添加
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        dialog.show();
    }

}
